package com.example.dbdesign.utils;

import com.fasterxml.jackson.databind.ser.Serializers;
import io.jsonwebtoken.*;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/***
 * @author: Nonlinear_fish
 * @date:2025-06-19.15:20
 * @description: jwt工具类
 */
public class JwtUtil {
    // 设置有效期
    public static final Long JWT_TLE = 60 * 60 * 1000L;
    // 设置密钥明文
    public static final String JWT_KEY = "MingWen";

    public static String getUUID(){
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        return token;
    }

    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalSecretKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if (ttlMillis == null){
            ttlMillis = JWT_TLE;
        }
        long expMillis = nowMillis + ttlMillis;
        Date exp = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid)
                .setSubject(subject)
                .setIssuer("J")
                .setIssuedAt(now)
                .signWith(signatureAlgorithm, secretKey)
                .setExpiration(exp);
    }

    /**
     * 生成JWT
     * @param subject 存放的数据
     * @param ttlMillis 超时时间
     * @return JWT
     */
    public static String createJWT(String subject, Long ttlMillis){
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());
        return builder.compact();
    }

    /**
     * 创建JWT
     * @param id id
     * @param subject 信息
     * @param ttlMillis 超时时间
     * @return JWT
     */
    public static String createJWT(String id, String subject, Long ttlMillis){
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);
        return builder.compact();
    }
    /**
     * 生成加密后密钥
     * @return key
     */
    private static SecretKey generalSecretKey(){
        byte[] encodeKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKey key = new SecretKeySpec(encodeKey, 0, encodeKey.length, "AES");
        return key;
    }

    public static Claims parseJWT(String jwt){
        SecretKey key = generalSecretKey();
        return Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwt)
                .getBody();
    }

    public static void main(String[] args) throws Exception {
        String token = JwtUtil.createJWT("01", "02", 60 * 60 * 12L);
        Claims claims = parseJWT(token);
        System.out.println(claims + "\n" + token + "\n" + claims.getId());
    }
}
